package com.masterclient.app.modules.purchase;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eoner.baselibrary.base.FragmentHostActivity;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.widget.CommonTabLayout;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.modules.order.OrderListFragment;
import com.masterclient.app.modules.purchase.adapter.PurchaseOrderTypeAdapter;
import com.masterclient.app.modules.purchase.widget.GuidePurchaseOrderDialog;
import com.masterclient.app.modules.shop.adapter.CommonViewPagerAdapter;
import com.masterclient.app.widget.MyPopupWindow;
import com.gyf.immersionbar.ImmersionBar;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @auther hjian
 * @date 2020/9/18.
 */
@Route(path = AroutePath.PURCHASE_ORDERS_ACTIVITY)
public class PurchaseOrdersActivity extends BaseActivity {

    @BindView(R.id.purchase_orders_bg)
    ImageView purchaseOrdersBg;
    @BindView(R.id.purchase_orders_back)
    FrameLayout purchaseOrdersBack;
    @BindView(R.id.purchase_orders_title)
    TextView purchaseOrdersTitle;
    @BindView(R.id.purchase_orders_title_arrow)
    ImageView purchaseOrdersTitleArrow;
    @BindView(R.id.purchase_orders_after_sale)
    TextView purchaseOrdersAfterSale;
    @BindView(R.id.purchase_orders_desc)
    TextView purchaseOrdersDesc;
    @BindView(R.id.purchase_orders_tab)
    CommonTabLayout purchaseOrdersTab;
    @BindView(R.id.purchase_orders_content)
    ViewPager purchaseOrdersContent;

    @Autowired(name = "from_type")
    String fromType;
    @Autowired(name = "position")
    int position = 0;

    String[] strings = {"全部","零售订单","采购订单"};
    private List<String> tabs;
    private List<Fragment> fragments;
    private MyPopupWindow popupMenu;
    private String titleType = "";
    private CommonViewPagerAdapter viewPagerAdapter;


    String action = "refreshUnComemtedFagment";

    private BroadcastReceiver mBoradcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(action)) {
                if (fragments != null && viewPagerAdapter != null && purchaseOrdersContent!= null) {
                    for (int i = 0; i < tabs.size(); i++) {
                        Fragment fragment = fragments.get(i);
                        if (fragment instanceof OrderListFragment){
                            ((OrderListFragment)fragment).refresh();
                        }
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_purchase_orders);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        ImmersionBar.with(this).init();

        int statusHeight = ImmersionBar.getStatusBarHeight(this);
        ((ConstraintLayout.LayoutParams)purchaseOrdersBack.getLayoutParams()).topMargin = statusHeight;
        ((ConstraintLayout.LayoutParams)purchaseOrdersBg.getLayoutParams()).height = statusHeight + ScreenUtils.dp2px(84);


        if (fromType.equals("purchase")){
            titleType = "";
            purchaseOrdersTitle.setText("采购订单");
            purchaseOrdersAfterSale.setText("售后退款");
            purchaseOrdersBg.setImageResource(R.mipmap.purchase_order_head_bg);
            purchaseOrdersTitleArrow.setVisibility(View.GONE);
            purchaseOrdersDesc.setVisibility(View.GONE);
            purchaseOrdersTab.setBackgroundResource(R.drawable.shape_round_top_white);
            if (SPUtils.getInstance().getBoolean(Config.IS_FIRST_PURCHASE_ORDER,true)){
                new GuidePurchaseOrderDialog(this).show();
                SPUtils.getInstance().put(Config.IS_FIRST_PURCHASE_ORDER, false);
            }
        }else {
            purchaseOrdersTitle.setText("全部");
            purchaseOrdersAfterSale.setText("处理售后");
            purchaseOrdersBg.setImageResource(R.mipmap.sale_order_head_bg);
            titleType = "1";
            purchaseOrdersTitleArrow.setVisibility(View.VISIBLE);
            purchaseOrdersDesc.setVisibility(View.VISIBLE);
            purchaseOrdersTab.setBackgroundResource(R.color.white);
//            if (SPUtils.getInstance().getBoolean(Config.IS_FIRST_SALE_ORDER,true)){
//                new GuideSaleOrderDialog(this).show();
//                SPUtils.getInstance().put(Config.IS_FIRST_SALE_ORDER, false);
//            }
        }

        tabs = Arrays.asList(getResources().getStringArray(R.array.purchase_order_tabs_name));
        fragments = new ArrayList<>();

        for (int i = 0; i < tabs.size(); i++) {
            purchaseOrdersTab.addTab(tabs.get(i), i == 0);
            fragments.add(OrderListFragment.getInstance(getResources().getStringArray(R.array.purchase_order_tabs_code)[i],"",fromType,titleType));
        }

        viewPagerAdapter = new CommonViewPagerAdapter
                (getSupportFragmentManager(), fragments, tabs);
        purchaseOrdersContent.setAdapter(viewPagerAdapter);
        purchaseOrdersContent.addOnPageChangeListener(new TabLayout.
                TabLayoutOnPageChangeListener(purchaseOrdersTab.getTabLayout()));
        purchaseOrdersTab.setupWithViewPager(purchaseOrdersContent);

        purchaseOrdersContent.setCurrentItem(position);


        IntentFilter filter = new IntentFilter();
        filter.addAction(action);
        registerReceiver(mBoradcastReceiver, filter);


    }

    public void setDesc(String desc){
        if (TextUtils.isEmpty(desc)){
            purchaseOrdersDesc.setVisibility(View.GONE);
        }else {
            purchaseOrdersDesc.setText(desc);
            purchaseOrdersDesc.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.purchase_orders_back, R.id.purchase_orders_title, R.id.purchase_orders_title_arrow, R.id.purchase_orders_after_sale})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.purchase_orders_back:
                finish();
                break;
            case R.id.purchase_orders_title:
            case R.id.purchase_orders_title_arrow:
                if ("sale".equals(fromType)){
                    showMenu(purchaseOrdersTitle);
                }
                break;
            case R.id.purchase_orders_after_sale:
                if (fromType.equals("purchase")){
                    ARouter.getInstance().build(AroutePath.AFTER_SALE_PURCHASE_LIST_ACTIVITY).navigation();
                }else {
                    Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.AFTER_SALE_SERVE_FRAGMENT)
                            .navigation();
                    FragmentHostActivity.openFragment(mContext, fragment);
                }
                break;
        }
    }



    // 操作功能弹窗
    private void showMenu(View view){
        if (popupMenu == null) {
            View menuView = View.inflate(this, R.layout.pop_purchase_order_type, null);
            RecyclerView recyclerView = menuView.findViewById(R.id.pop_purchase_type_recycler);
            recyclerView.setLayoutManager(new LinearLayoutManager(this) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            PurchaseOrderTypeAdapter menuAdapter = new PurchaseOrderTypeAdapter(Arrays.asList(strings));
            recyclerView.setAdapter(menuAdapter);

            menuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    menuAdapter.setSelectPos(position);
                    purchaseOrdersTitle.setText(strings[position]);
                    titleType = String.valueOf(position+1);
                    popupMenu.dismiss();
                    fragments.clear();
                    for (int i = 0; i < tabs.size(); i++) {
                        fragments.add(OrderListFragment.getInstance(getResources().getStringArray(R.array.purchase_order_tabs_code)[i],"",fromType,titleType));
                    }
                    purchaseOrdersContent.setCurrentItem(0);
                    viewPagerAdapter.clear(purchaseOrdersContent);
                    purchaseOrdersContent.setAdapter(viewPagerAdapter);
                   }
            });
            int popupHeight = ScreenUtils.dp2px(10 + 44 * 3);
            popupMenu = new MyPopupWindow.Builder(this)
                    .setIsShowBg(false)
                    .setParams(ViewGroup.LayoutParams.MATCH_PARENT, popupHeight)
                    .setView(menuView)
                    .setOutSideCancel(true)
                    .setContentViewClickListener(null).build();
            popupMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    purchaseOrdersTitleArrow.setRotation(90);
                }
            });
        }
        purchaseOrdersTitleArrow.setRotation(270);
        popupMenu.showVerticalAutomatic(view,0,0);
    }
}
